package com.ctgu.server.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctgu.server.dao.constant.CacheKey;
import com.ctgu.server.dao.dto.AttendanceTimeSlotDto;
import com.ctgu.server.dao.dto.RecordDto;
import com.ctgu.server.dao.entity.AttendanceLocation;
import com.ctgu.server.dao.entity.AttendanceRecord;
import com.ctgu.server.dao.entity.AttendanceTimeSlot;
import com.ctgu.server.dao.vo.Result;
import com.ctgu.server.mapper.AttendanceRecordMapper;
import com.ctgu.server.service.AttendanceRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.server.utils.ResultUtil;
import com.ctgu.server.utils.clock.LocationUtils;
import net.oschina.j2cache.CacheChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 考勤记录表 服务实现类
 * </p>
 *
 * @author ctgu
 * @since 2023-06-13
 */
@Service
public class AttendanceRecordServiceImpl extends ServiceImpl<AttendanceRecordMapper, AttendanceRecord> implements AttendanceRecordService {

    @Autowired
    private CacheChannel cacheChannel;
    @Autowired
    private AttendanceGroupServiceImpl attendanceGroupService;
    @Autowired
    private AttendanceTimeSlotServiceImpl attendanceTimeSlotService;

    @Autowired
    private AttendanceLocationServiceImpl attendanceLocationService;




    @Override
    public Result clockInRecord(RecordDto recordDto) {
        if (attendanceGroupService.getById(recordDto.getAttGroupId())==null) {
            return ResultUtil.error("打卡组不存在");
        }
        //
        //获取打卡地点参数
        List<AttendanceLocation> locationList= (List<AttendanceLocation>) cacheChannel.get(CacheKey.Clock_Redis,"l"+recordDto.getAttGroupId()).getValue();
        if(locationList==null){
            LambdaQueryWrapper<AttendanceLocation> locationLambdaQueryWrapper=new LambdaQueryWrapper<>();
            locationLambdaQueryWrapper.eq(AttendanceLocation::getAttendanceGroupId,recordDto.getAttGroupId());
            locationList=attendanceLocationService.list(locationLambdaQueryWrapper);
            cacheChannel.set(CacheKey.Clock_Redis,"l"+recordDto.getAttGroupId(),locationList);
        }
        //参数效验
        int count=0;
        String locationId="";
        if(locationList.size()!=0){
            for(AttendanceLocation attendanceLocation:locationList){
                if (LocationUtils.distance(recordDto.getLongitude(),recordDto.getLatitude(),attendanceLocation)) {
                    count++;
                    locationId=attendanceLocation.getId();
                    break;
                }
            }
            if(count==0){
                return ResultUtil.error("不在打卡范围");
            }

        }
        count=0;
        //获取打卡时间段参数
        List<AttendanceTimeSlot> timeList= (List<AttendanceTimeSlot>) cacheChannel.get(CacheKey.Clock_Redis,"t"+recordDto.getAttGroupId()).getValue();
        if(timeList==null){
            LambdaQueryWrapper<AttendanceTimeSlot> timeSlotLambdaQueryWrapper=new LambdaQueryWrapper<>();
            timeSlotLambdaQueryWrapper.eq(AttendanceTimeSlot::getGroupId,recordDto.getAttGroupId());
            timeList= attendanceTimeSlotService.list(timeSlotLambdaQueryWrapper);
            cacheChannel.set(CacheKey.Clock_Redis,"t"+recordDto.getAttGroupId(),timeList);
        }

        AttendanceTimeSlot attendanceTimeSlot = null;
        LocalTime currentTime=LocalTime.now();
        if(timeList.size()!=0){
            //获取当前时间

            for(AttendanceTimeSlot attendanceTimeSlot1:timeList){
                if (!currentTime.isAfter(attendanceTimeSlot1.getStartTime().toLocalTime())) {
                    continue;
                }
                if(currentTime.isBefore(attendanceTimeSlot1.getEndTime().toLocalTime())){
                    attendanceTimeSlot=attendanceTimeSlot1;
                    count++;
                    break;
                }
            }
            if(count==0){
                return ResultUtil.error("超出打卡时间！");
            }
        }
        //检查用户是第几次打卡
        LambdaQueryWrapper<AttendanceRecord> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AttendanceRecord::getGroupId,recordDto.getAttGroupId())
                .eq(AttendanceRecord::getUserId,recordDto.getUserId()).eq(AttendanceRecord::getAttendanceDate,DateTime.now());
        if(attendanceTimeSlot!=null){
             lambdaQueryWrapper.eq(AttendanceRecord::getTimeSlotId,attendanceTimeSlot.getId());
        }


        AttendanceRecord attendanceRecord=this.getOne(lambdaQueryWrapper,false);
        if(attendanceRecord==null){
            //当用户是第一次打卡的时候
            attendanceRecord=new AttendanceRecord();
            attendanceRecord.setUserId(recordDto.getUserId());
            attendanceRecord.setGroupId(recordDto.getAttGroupId());

            attendanceRecord.setStatus("正常打卡");
            attendanceRecord.setAttendanceDate(DateTime.now());
            attendanceRecord.setCreateTime(Time.valueOf(currentTime));
            if(!locationId.isEmpty()){
                attendanceRecord.setLocationId(locationId);
            }
            if(attendanceTimeSlot!=null){
                attendanceRecord.setTimeSlotId(attendanceTimeSlot.getId());
            }
            attendanceRecord.setUpdateTime(Time.valueOf(currentTime));
            //添加用户打卡记录
            this.saveOrUpdate(attendanceRecord);
            return ResultUtil.success();
        }
        attendanceRecord.setUpdateTime(Time.valueOf(currentTime));
        this.updateById(attendanceRecord);







        return ResultUtil.success();
    }
}
